package com.lais.record.user.properties;

import com.lais.record.common.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @Author: luowen
 * @Description: JWT属性配置
 * @Date: Create in 16:42 2019/11/30
 */
@ConfigurationProperties(prefix = "record.jwt")
@Data
@Slf4j
@Component
public class JwtProperties {

    private String secret; //密钥

    private String pubKeyPath;// 公钥

    private String priKeyPath;// 私钥

    private int expire;// token过期时间

    private PublicKey publicKey;

    private PrivateKey privateKey;

    @PostConstruct
    public void init(){
        try {
            File pubKey = new File(pubKeyPath);
            File priKey = new File(priKeyPath);
            //获取文件的父级目录
            String parent = pubKey.getParent();
            File file = new File(parent);
            //若父级目录不存在，则创建文件夹
            if(!file.exists()){
                file.mkdirs();
            }
            if (!pubKey.exists() || !priKey.exists()) {
                // 生成公钥和私钥
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            log.error("初始化公钥和私钥失败！", e);
            throw new RuntimeException();
        }
    }
}
